package com.pallass.admin.controller;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pallass.admin.domain.SysResource;
import com.pallass.admin.domain.SysRole;
import com.pallass.admin.service.SysResourceService;
import com.pallass.admin.service.SysRoleService;
import com.pallass.common.controller.BaseController;
import com.pallass.common.jpa.criteria.OperatorType;
import com.pallass.common.jpa.domain.ListSpecificationBuilder;
import com.pallass.utils.RequestResult;

/**
 * 角色
 * 
 * @author Houor
 *
 * @createTime: 2017-03-01 10:23
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController extends BaseController {
	
	private static Logger logger = LoggerFactory.getLogger(RoleController.class);

	@Autowired
	private SysRoleService roleService;

	@Autowired
	private SysResourceService resourceService;

	@RequestMapping(value = "/index")
	public String index(Model model) {
		model.addAttribute("purl", "admin/role");
		return "admin/role";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Page<SysRole> list() {

		ListSpecificationBuilder<SysRole> builder = new ListSpecificationBuilder<SysRole>();
		String roleName = request.getParameter("roleName");
		if (StringUtils.isNotBlank(roleName)) {
			builder.add("roleName", OperatorType.LIKE, roleName);
		}

		return roleService.findAll(builder.generateListSpecification(), getPageRequest());
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public RequestResult save(@RequestBody SysRole role) {
		if (StringUtils.isBlank(role.getRoleKey())) {
			return RequestResult.failure("角色标识不能为空");
		}
		if (StringUtils.isBlank(role.getRoleName())) {
			return RequestResult.failure("角色名称字不能为空");
		}
		roleService.save(role);
		return RequestResult.success("添加角色成功");
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	@ResponseBody
	public SysRole edit(@PathVariable Integer id) {
		return roleService.findOne(id);
	}

	@RequestMapping(value = "/update")
	@ResponseBody
	public RequestResult update(@RequestBody SysRole role) {
		if (StringUtils.isBlank(role.getRoleKey())) {
			return RequestResult.failure("角色标识不能为空");
		}
		if (StringUtils.isBlank(role.getRoleName())) {
			return RequestResult.failure("角色名称字不能为空");
		}
		roleService.update(role);
		return RequestResult.success("修改角色成功");
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public RequestResult delete(@RequestBody Integer ids[]) {

		try {
			roleService.deleteByIdArray(ids);
		} catch (org.springframework.dao.DataIntegrityViolationException e) {
			logger.debug("Role delete failure. DataIntegrityViolationException");
			return RequestResult.failure("该角色已分配, 请确认后再行删除");
		}

		return RequestResult.success("删除角色成功");
	}

	@RequestMapping(value = "/grant/{id}", method = RequestMethod.GET)
	@ResponseBody
	public SysResource grant(@PathVariable Integer id) {

		List<SysResource> resourceList = resourceService.findAll();
		Set<SysResource> roleSet = roleService.findOne(id).getResources();
		if (roleSet != null && roleSet.size() > 0) {
			for (SysResource r : resourceList) {
				if (roleSet.contains(r)) {
					r.setChecked(true);
				}
			}
		}

		// 构造父子树
		SysResource root = new SysResource();
		root.setId(0);
		root.setResourceName("根资源");
		root.setOpen(true);

		for (SysResource sr : resourceList) {
			if (sr.getParent() == null) {
				root.getChildren().add(sr);
			} else {
				sr.getParent().getChildren().add(sr);
				sr.setParent(null);
			}
		}
		return root;
	}

	@RequestMapping(value = "/grant/{id}", method = RequestMethod.POST)
	@ResponseBody
	public RequestResult grant(@PathVariable Integer id, @RequestBody(required = false) Integer[] resourceIds) {

		try {
			roleService.grant(id, resourceIds);
		} catch (org.springframework.dao.DataIntegrityViolationException e) {
			logger.info("grant resource to role failure. (DataIntegrityViolationException)");
			return RequestResult.failure("资源分配失败");
		}

		return RequestResult.success("资源分配成功");
	}
}
